import { defineStore } from "pinia";
import api from "@/api";
import router from "@/router";
import type { get } from "@vueuse/core";

// 为什么要在这里添加令牌验证？作为最后的安全保障
const validateToken = (token: string | null): boolean => {
  if (!token) return false;
  // 可以添加简单的令牌格式验证
  return token.length > 10; // 假设有效的令牌至少有10个字符
};

export const userInfo = defineStore("userInfo", {
  state: () => ({
    userInfo: {
      userId: "",
      userName: "",
      nickname: "",
      accessToken: "",
      refreshToken: "",
      avatarUrl: "",
      roleId: "",
    },
    menuList: [],
    onGoingContest: null, // 当前进行中的比赛
  }),

  getters: {
    getUserId: (state: any) => state.userInfo.userId,
    getUserName: (state: any) => state.userInfo.userName,
    getNickname: (state: any) => state.userInfo.nickname,
    getToken: (state: any) => state.userInfo.accessToken,
    getRefreshToken: (state: any) => state.userInfo.refreshToken,
    getAvatarUrl: (state: any) => state.userInfo.avatarUrl,
    getRole: (state: any) => state.userInfo.roleId,
    getMenuList: (state: any) => state.menuList,
    getOnGoingContest: (state: any) => state.onGoingContest,
    // 添加令牌有效性检查getter
    isTokenValid: (state: any) => validateToken(state.userInfo.accessToken),
  },
  actions: {
    initAuthState() {// 初始化认证状态的核心方法，应用启动时调用
    // 1. 确定用户选择的存储类型（持久化/会话级）
      const localRememberMe = localStorage.getItem('rememberMe') === 'true'; // 检查localStorage中的rememberMe标志
      const sessionRememberMe = sessionStorage.getItem('rememberMe') === 'true';// 检查sessionStorage中的rememberMe标志
// 2. 选择正确的存储对象（优先使用localStorage，因为用户可能同时设置了两种存储）
      const storage = localRememberMe ? localStorage : sessionStorage;
       // 3. 从目标存储中获取令牌信息
       // 双令牌机制需要同时验证访问令牌和刷新令牌的有效性
      const accessToken = storage.getItem('accessToken');// 获取访问令牌
      const refreshToken = storage.getItem('refreshToken');// 获取刷新令牌
 // 4. 验证令牌有效性并加载用户信息
 // 防止单一令牌被篡改或过期导致的安全风险
      if (accessToken && refreshToken && validateToken(accessToken)) {// 令牌存在且有效
        // 确保应用状态与存储数据一致，避免重复登录
        this.userInfo.accessToken = accessToken;
        this.userInfo.refreshToken = refreshToken;
        this.userInfo.userId = storage.getItem('userId') || "";
        this.userInfo.nickname = storage.getItem('nickname') || "";
        this.userInfo.avatarUrl = storage.getItem('avatarUrl') || "";
        this.userInfo.roleId = storage.getItem('roleId') || "";
      } else if (accessToken || refreshToken) {
        // 如果存在无效令牌，清除存储
        console.log("[userInfo] 检测到无效令牌，清除存储");
        this.clearStorage();
      }
    },
    
    async login(loginData: any) {
      try {
        const res = await api.userLogin.login(loginData);

        if (res.code !== 200) {
          throw new Error(res.msg || "登录失败200");
        }

        // 验证返回的令牌
        if (!res.data.accessToken || !validateToken(res.data.accessToken)) {
          throw new Error("获取的访问令牌无效");
        }

        this.userInfo.userId = res.data.userId;
        this.userInfo.nickname = res.data.nickname;
        this.userInfo.avatarUrl = res.data.avatarUrl || "";
        this.userInfo.roleId = res.data.roleId || "";
        this.userInfo.userName = loginData.userName;
        this.userInfo.accessToken = res.data.accessToken;
        this.userInfo.refreshToken = res.data.refreshToken || '';

        // 根据rememberMe选择存储方式
        const storage = loginData.rememberMe ? localStorage : sessionStorage;
        storage.setItem('rememberMe', loginData.rememberMe.toString());
        storage.setItem('accessToken', res.data.accessToken);
        storage.setItem('refreshToken', res.data.refreshToken || '');
        storage.setItem('userId', res.data.userId);
        storage.setItem('nickname', res.data.nickname || '');
        storage.setItem('avatarUrl', res.data.avatarUrl || '');
        storage.setItem('roleId', res.data.roleId || '');

        console.log("登录成功:", this.userInfo);
        return res;
      } catch (error) {
        console.error("登录失败:", error);
        throw error;
      }
    },
    
    async logout() {
    try {
        // 1. 调用后端登出接口
        const refreshToken = this.userInfo.refreshToken;
        if (refreshToken) {
            await api.userLogin.logout(refreshToken);
            console.log("后端登出成功");
        }
    } catch (error) {
        console.error("后端登出失败:", error);
        // 即使后端调用失败，仍然执行本地登出
    } finally {
        // 2. 清除本地存储
        this.clearStorage();
        // 3. 重置用户信息
        this.userInfo = {
            userId: "",
            userName: "",
            nickname: "",
            accessToken: "",
            refreshToken: "",
            avatarUrl: "",
            roleId: "",
        };
        // 4. 重定向到登录页
        router.push('/login');
    }
},
    
    // 新增：清除存储的令牌信息
    clearStorage() {
      // 清除localStorage
      localStorage.removeItem('rememberMe');
      localStorage.removeItem('accessToken');
      localStorage.removeItem('refreshToken');
      localStorage.removeItem('userId');
      localStorage.removeItem('nickname');
      localStorage.removeItem('avatarUrl');
      localStorage.removeItem('roleId');

      // 清除sessionStorage
      sessionStorage.removeItem('rememberMe');
      sessionStorage.removeItem('accessToken');
      sessionStorage.removeItem('refreshToken');
      sessionStorage.removeItem('userId');
      sessionStorage.removeItem('nickname');
      sessionStorage.removeItem('avatarUrl');
      sessionStorage.removeItem('roleId');
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'pinia-userinfo',
        storage: localStorage,
        paths: [],
      },
    ],
  },
});